package com.sysu.minsysu.zdkb;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.sysu.R;
import com.sysu.minsysu.zdkb.utils.ClassTimeConflictException;
import com.sysu.minsysu.zdkb.utils.Course;
import com.sysu.minsysu.zdkb.utils.CourseUtils;
import com.sysu.minsysu.zdkb.utils.ProCourse;

public class SelectCoursesActivity extends Activity {

	private static final String TAG = "CalContentDemo";

	private static final String COURSECOUNT = "courseCount";
	private static final String COURSEEID = "courseEid";
	
	private static final int SHOWQUERYRESULT = 3;
	
	
	ContentResolver mContentResolver;
	Cursor mCursor;

	ExpandableListView mListView;
	Button mCommitButton;
	Button mCancelButton;

	ArrayList<Course>[] mCoursesList;
	ArrayList<Course> mPubRequireCourseList;
	ArrayList<Course> mPubElectiveCourseList;
	ArrayList<ProCourse> mProRequireCourseList;
	ArrayList<ProCourse> mProElectiveCourseList;

	CourseExpandableAdapter mAdapter;

	
	boolean[][] mSelectedCourse;
	boolean[][] mOrigenCourse;
	
	int mCourseCount=0;
	String[] mCourseEventEid;
	
	Course[] mSavedCourses;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_courses);
		
		setupViews();
		setupCourses();
		getSavedClassState();
	}
	
	@Override
	protected void onNewIntent(Intent intent){
		setIntent(intent);
		Log.d(TAG, intent.getAction() );
		if( Intent.ACTION_VIEW.equals(intent.getAction())){
			long courseId = Long.parseLong( intent.getDataString() );
			int[] pos = findCoursePosWithCourseId(courseId);
//			Log.d(TAG, pos[0] + " " + pos[1]);
//			Log.d(TAG, "courseId = " + courseId);
			showCourseDetail( mCoursesList[pos[0]].get(pos[1]));
			
		}else if( Intent.ACTION_SEARCH.equals( intent.getAction() )){
			String queryText = intent.getStringExtra( SearchManager.QUERY );
			Intent newActiviryIntent = new Intent(this, SearchResultList.class);
			newActiviryIntent.putExtra(SearchResultList.COURSES, findCoursesWithName(queryText));
			startActivityForResult(newActiviryIntent, SHOWQUERYRESULT);
		}
	}
	
	@Override
	protected void onActivityResult( int requestCode, int resultCode, Intent data ){
		if( requestCode==SHOWQUERYRESULT ){
			if( resultCode==RESULT_OK ){
				ArrayList<Integer> selectedNums = (ArrayList<Integer>)data.getSerializableExtra("result");
				for( Integer num : selectedNums ){
					int[] temp = findCoursePosWithCourseId(num);
					mSelectedCourse[ temp[0] ][ temp[1] ] = true;
				}
				mAdapter.notifyDataSetChanged();
			}
		}
	}
	
	private ArrayList<Course> findCoursesWithName( String name ){
		ArrayList<Course> result = new ArrayList<Course>();
		for( int i=0; i<4; i++ ){
			ArrayList<Course> tempList = mCoursesList[i];
			for( Course course : tempList)
				if( course.getCourseName().contains(name))
					result.add(course);
		}
		return result;
	}
	
	private void getSavedClassState(){
		mSavedCourses = CourseUtils.getSelectCoursesInCalendar(this);
		
		for( int k=0; k<mSavedCourses.length; k++ ){
			Course savedCourse = mSavedCourses[k];
			for( int i=0; i<4; i++ ){
				ArrayList<Course> tempCourseList = mCoursesList[i];
				int j=0;
				for( Course course : tempCourseList ){
					if( savedCourse.equals(course) ){
						mSelectedCourse[i][j] = true;
					}
					j++;
				}
			}
		}
		
		mOrigenCourse = new boolean[4][];
		for( int i=0; i<4; i++ )
			mOrigenCourse[i] = mSelectedCourse[i].clone();
		
	}

	private void setupCourses() {
		mCoursesList = CourseUtils.getClassTimetable(this, null );
		mPubRequireCourseList = mCoursesList[0];
		mPubElectiveCourseList = mCoursesList[1];
		mProRequireCourseList = (ArrayList<ProCourse>) (Object) (mCoursesList[2]);
		mProElectiveCourseList = (ArrayList<ProCourse>) (Object) mCoursesList[3];


		mSelectedCourse = new boolean[4][];
		for( int i=0; i<4; i++ )
			mSelectedCourse[i] = new boolean[ mCoursesList[i].size() ];
		
		for (ArrayList<Course> courses : mCoursesList) {
			mCourseCount += courses.size();
		}
		mAdapter = new CourseExpandableAdapter(this);
		mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		mListView.setAdapter(mAdapter);
	}
	
	private void setupViews() {
		mListView = (ExpandableListView) findViewById(R.id.listview);
		mCommitButton = (Button) findViewById(R.id.commit);
		mCancelButton = (Button) findViewById(R.id.cancel);
		mCommitButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ArrayList<Course> coursesToAdd = new ArrayList<Course>();
				ArrayList<Course> coursesToDelete = new ArrayList<Course>();
				for( int i=0; i<4; i++ ){
					for( int j=0; j<mSelectedCourse[i].length; ++j ){
						// 找到增加的课程
						if( mSelectedCourse[i][j]==true && mOrigenCourse[i][j]==false){
							coursesToAdd.add( mCoursesList[i].get(j));
							mOrigenCourse[i][j] = true;
						}
						
						// 找到删除的课程
						else if ( mSelectedCourse[i][j]==false && mOrigenCourse[i][j]==true) {
							mOrigenCourse[i][j] = false;
							for( Course course : mSavedCourses ){
								if( mCoursesList[i].get(j).equals(course)){
									coursesToDelete.add(course);
									break;
								}
							}
						}
						
					}
				}
				//删除已有的课程
				Course[] coursesToDeleteArray = new Course[coursesToDelete.size()];
				for( int i=0; i<coursesToDeleteArray.length; i++ ){
					coursesToDeleteArray[i] = coursesToDelete.get(i);
				}
				CourseUtils.delectExistingCourse(SelectCoursesActivity.this, coursesToDeleteArray);
				
				//添加新课程
				Course[] courseToAddArray = new Course[coursesToAdd.size()];
				for (int i = 0; i < courseToAddArray.length; i++)
					courseToAddArray[i] = coursesToAdd.get(i);

				try {
					CourseUtils.addNewCourses(SelectCoursesActivity.this, courseToAddArray, false );
				} catch (ClassTimeConflictException e) {
					handleClassConflict(e, courseToAddArray);
				}
				
				AlertDialog.Builder builder = new AlertDialog.Builder(SelectCoursesActivity.this);
				builder.setTitle("修改成功");
				builder.setMessage("是否前去查看我的课表");
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(SelectCoursesActivity.this, MyCourseActivity.class);
						startActivity(intent);
					}
				});
				builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				builder.show();
				
				Toast.makeText(SelectCoursesActivity.this, "修改成功", Toast.LENGTH_LONG).show();
			}
		});
		
		mCancelButton.setOnClickListener( new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	private void handleClassConflict( ClassTimeConflictException e, final Course[] courseArray){
		AlertDialog.Builder builder = new AlertDialog.Builder( SelectCoursesActivity.this );
		builder.setTitle("确认");
		builder.setMessage( e.course1.getCourseName() + "与" + e.course2.getCourseName() + "课程时间冲突，是否继续？");
		builder.setPositiveButton("继续",  new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try {
					CourseUtils.addNewCourses(SelectCoursesActivity.this, courseArray, true);
				} catch (ClassTimeConflictException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		builder.setNegativeButton("取消",  new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {}
		});
		builder.create().show();
	}

	class CourseExpandableAdapter extends BaseExpandableListAdapter {

		private Context context;
		private LayoutInflater mLayoutInflater;

		public CourseExpandableAdapter(Context context) {
			this.context = context;
			mLayoutInflater = LayoutInflater.from(context);
			
		}
		

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return mCoursesList[groupPosition].get(childPosition);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return mCoursesList[groupPosition].get(childPosition).getId();
		}

		@Override
		public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
			
			ViewHolder holder;
			
				convertView = mLayoutInflater.inflate(R.layout.courseview, null);
				holder = new ViewHolder();
				holder.selectBox = (CheckBox) convertView.findViewById(R.id.selectBox);
				holder.courseNameTextView = (TextView) convertView.findViewById(R.id.courseName);
				holder.teacherNameTextView = (TextView) convertView.findViewById(R.id.teacherName);
				holder.timeTextView = (TextView) convertView.findViewById(R.id.courseTime);
				holder.showDetailButton = (Button) convertView.findViewById(R.id.showDetail);
				//convertView.setTag(holder);
			
			final Course course = mCoursesList[groupPosition].get(childPosition);
			holder.selectBox.setChecked(mSelectedCourse[groupPosition][childPosition]);
			holder.selectBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					mSelectedCourse[groupPosition][childPosition] = isChecked;
				}
			});
			
			holder.showDetailButton.setOnClickListener( new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					showCourseDetail(course);
				}
			});
			
			holder.courseNameTextView.setText(course.getCourseName());
			holder.teacherNameTextView.setText(course.getTeacherName());
			holder.timeTextView.setText( course.getDate() + " " + course.getClassInterval());

			return convertView;
		}

		private class ViewHolder {
			CheckBox selectBox;
			TextView courseNameTextView;
			TextView teacherNameTextView;
			TextView timeTextView;
			Button showDetailButton;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return mCoursesList[groupPosition].size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return mCoursesList[groupPosition];
		}

		@Override
		public int getGroupCount() {
			return mCoursesList.length;
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
			TextView textView = getGenericView();
			String groupName = null;
			switch (groupPosition) {
			case 0:
				groupName = "公必课";
				break;
			case 1:
				groupName = "公选课";
				break;
			case 2:
				groupName = "专必课";
				break;
			case 3:
				groupName = "专选课";
				break;
			}
			textView.setText(groupName);

			return textView;

		}

		public TextView getGenericView() {
			AbsListView.LayoutParams lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 64);

			TextView textView = new TextView(context);
			textView.setLayoutParams(lp);
			textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
			textView.setPadding(36, 0, 0, 0);
			return textView;
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}
	}
	
	private void showCourseDetail( final Course course ){
		final DetailsDialog dialog = new DetailsDialog(SelectCoursesActivity.this, course );
		dialog.setSelectListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				int[] pos = findCoursePosWithCourseId(course.getId());
				mSelectedCourse[ pos[0] ][ pos[1] ] = true;
				mAdapter.notifyDataSetChanged();
				dialog.dismiss();
			}
		});
		dialog.show();
	}
	
	private ArrayList<Course> getSelectedCourse(){
		ArrayList<Course> result = new ArrayList<Course>();
		for( int i=0; i<4; i++ ){
			ArrayList<Course> courses = mCoursesList[i];
			
			for( int j=0; j<courses.size(); j++ ){
				if( mSelectedCourse[i][j] )
					result.add(courses.get(j));
			}
		}
		return result;
	}
	
	private int[] findCoursePosWithCourseId( long id ){
		for( int i=0; i<4; i++ ){
			ArrayList<Course> courseList = mCoursesList[i];
			for( int j=0; j<courseList.size(); j++ ){
				if( courseList.get(j).getId() == id ){
					return new int[]{ i, j };
				}
			}
		}
		return new int[]{-1,-1};
	}

}